package com.liuym.student.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.liuym.common.annotation.StudentLogin;
import com.liuym.common.annotation.StudentLoginUser;
import com.liuym.common.constants.Constants;
import com.liuym.common.constants.GradeResponse;
import com.liuym.common.dubbo.classes.api.ClassScoreDubboService;
import com.liuym.common.dubbo.classes.api.ClassesDubboService;
import com.liuym.common.dubbo.classes.dto.ClassDTO;
import com.liuym.common.dubbo.classes.dto.ClassScoreDTO;
import com.liuym.common.dubbo.table.api.TableNameDubboService;
import com.liuym.common.exception.StudentException;
import com.liuym.common.utils.DateUtil;
import com.liuym.student.repository.mapper.StudentMapper;
import com.liuym.student.repository.model.bo.StudentBO;
import com.liuym.student.repository.model.bo.StudentScoreBO;
import com.liuym.student.repository.model.entity.Student;
import com.liuym.student.repository.model.vo.StudentPlusVO;
import com.liuym.student.repository.model.vo.StudentVO;
import com.liuym.student.service.StudentScoreService;
import com.liuym.student.service.StudentService;
import com.vip.vjtools.vjkit.mapper.BeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author LiuYiMing
 * @date 2018/9/18 11:44
 * @describe：
 */
@StudentLogin
@RestController
@RequestMapping("/student")
public class StudentController {

    private static Logger logger = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentScoreService studentScoreService;

    @Autowired
    private StudentMapper studentMapper;

    @Reference(version = "${class.dubbo.version}")
    private ClassesDubboService classesDubboService;
    @Reference(version = "${class.dubbo.version}")
    private ClassScoreDubboService classScoreDubboService;
    @Reference(version = "${admin.dubbo.version}")
    private TableNameDubboService tableNameDubboService;

    @GetMapping("/findStudent")
    public GradeResponse findStudentByStudentNumber(@StudentLoginUser StudentVO studentVO) {
        StudentPlusVO studentPlusVO = new StudentPlusVO();
        List<StudentScoreBO> studentScoreList = null;
        ClassDTO classDTO = null;
        List<ClassScoreDTO> classScoreDTOList = null;
        List<StudentBO> studentBOList = null;
        if ((studentVO != null)) {
            //存入学生
            studentPlusVO.setStudentInfo(studentVO);
            //存入学生分数
            try {
                logger.info("开始调用findByTableAndTime");
                String tableName = tableNameDubboService.findByTableAndTime(Constants.STUDENT_SCORE_TABLE_NAME).getTableName();
                logger.info("调用findByTableAndTime结束,result:{}", tableName);
                studentScoreList = studentScoreService.getStudentScoreByStudentNumber(tableName, studentVO.getStudentNumber());
            } catch (Exception e) {
                if (e instanceof StudentException) {
                    logger.warn("error", e);
                    return GradeResponse.fail(((StudentException) e).getCode(), ((StudentException) e).getMsg());
                }
            }
            if (studentScoreList != null && studentScoreList.size() > 0) {
                studentPlusVO.setStudentScoreInfo(studentScoreList);
            }
            //存入班级信息
            try {
                logger.info("开始调用getClassByNumber，param：{}", studentVO.getClassNumber());
                classDTO = classesDubboService.getClassByNumber(studentVO.getClassNumber());
                logger.info("调用getClassByNumber结束，result：{}", classDTO);
            } catch (Exception e) {
                logger.error("调用getClassByNumber发生异常！", e);
            }
            if (classDTO != null) {
                studentPlusVO.setClassInfo(classDTO);
            }
            //存入班级分数
            try {
                logger.info("开始调用findByTableAndTime");
                String tableName = tableNameDubboService.findByTableAndTime(Constants.CLASS_SCORE_TABLE_NAME).getTableName();
                logger.info("调用findByTableAndTime结束,result:{}", tableName);
                classScoreDTOList = classScoreDubboService.getClassScoreByClassNumber(tableName, studentVO.getClassNumber());
            } catch (Exception e) {
                if (e instanceof StudentException) {
                    logger.warn("error", e);
                    return GradeResponse.fail(((StudentException) e).getCode(), ((StudentException) e).getMsg());
                }
            }
            if (classScoreDTOList != null && classScoreDTOList.size() > 0) {
                studentPlusVO.setClassScoreInfo(classScoreDTOList);
            }
            if ("班长".equals(studentVO.getDuty())) {
                try {
                    studentBOList = studentService.getStudentByClass(studentVO.getClassNumber());
                } catch (StudentException e) {
                    logger.warn("error", e);
                    return GradeResponse.fail(((StudentException) e).getCode(), ((StudentException) e).getMsg());
                }
                studentPlusVO.setStudentBOList(studentBOList);
            }
            return GradeResponse.success(studentPlusVO);
        } else {
            return GradeResponse.internalServerError();
        }
    }

    @PutMapping("/updateStudent")
    public GradeResponse uptateStudent(StudentVO studentVO) {
        int result = 0;
        StudentBO studentBO = BeanMapper.map(studentVO, StudentBO.class);
        try {
            result = studentService.updateStudent(studentBO);
        } catch (Exception e) {
            if (e instanceof StudentException) {
                logger.warn("warn", e);
                return GradeResponse.fail(((StudentException) e).getCode(), ((StudentException) e).getMsg());
            }
            logger.error("error", e);
            return GradeResponse.internalServerError();
        }
        return GradeResponse.success(result);
    }

    @PutMapping("/updatePassword")
    public GradeResponse updatePassword(StudentVO studentVO) {
        int result = 0;
        Student student = BeanMapper.map(studentVO, Student.class);
        try {
            result = studentMapper.updateByPrimaryKeySelective(student);
        } catch (Exception e) {
            if (e instanceof StudentException) {
                logger.warn("warn", e);
                return GradeResponse.fail(((StudentException) e).getCode(), ((StudentException) e).getMsg());
            }
            logger.error("error", e);
            return GradeResponse.internalServerError();
        }
        return GradeResponse.success(result);
    }

    @GetMapping("/findHistoryScore")
    public GradeResponse findHistoryScore(String term,@StudentLoginUser StudentVO studentVO) throws StudentException {
        Map<String, Object> historyScore = studentService.findHistoryScore(term, studentVO.getStudentNumber());
        historyScore.put("name",studentVO.getName());
        historyScore.put("term",term.substring(16,term.length()));
        return GradeResponse.success(historyScore);
    }

    @PostMapping("/logout")
    public GradeResponse logout(@RequestParam String token) {
        studentService.logout(token);
        return GradeResponse.success("操作成功", "");
    }

    @GetMapping("/findStudentScoreTable")
    public GradeResponse findStudentScoreTable() throws StudentException {
        List<String> studentScoreTableAll = studentScoreService.getStudentScoreTableAll();
        return GradeResponse.success(studentScoreTableAll);
    }
}
